<template>
  <div class="container-wrapper">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>折扣权益</span>
          <el-button type="primary" @click="add(1)">新增折扣权益</el-button>
        </div>
      </template>

      <!-- <BasicTable
        ref="discountTableRef"
        :api="getBenefitsListDiscount"
        :columns="discountColumns"
        :actionColumn="actionColumn"
        :pagination="false"
      >
        <template #actions="{ record }">
          <TableAction :actions="tableActions(record.row, 1)" />
        </template>
      </BasicTable> -->
      <TableList
        :columns="discountColumns"
        :tableData="benefitsData"
        :benefitsType="1"
        @edit="edit"
        @change-status="changeStatus"
        @delete="deleteData"
      />
    </el-card>

    <el-divider />

    <el-card>
      <template #header>
        <div class="card-header">
          <span>积分权益</span>
          <el-button type="primary" @click="add(2)">新增积分权益</el-button>
        </div>
      </template>

      <!-- <BasicTable
        ref="pointTableRef"
        :api="getBenefitsListPoint"
        :columns="pointColumns"
        :actionColumn="actionColumn"
        :pagination="false"
      >
        <template #actions="{ record }">
          <TableAction :actions="tableActions(record.row, 2)" />
        </template>
      </BasicTable> -->
      <TableList
        :columns="pointColumns"
        :tableData="pointTableData"
        :benefitsType="2"
        @edit="edit"
        @change-status="changeStatus"
        @delete="deleteData"
      />
    </el-card>

    <el-divider />

    <el-card>
      <template #header>
        <div class="card-header">
          <span>舌诊权益</span>
          <el-button type="primary" @click="add(3)">新增舌诊权益</el-button>
        </div>
      </template>
      <TableList
        :columns="tongueColumns"
        :tableData="tongueTableData"
        :benefitsType="3"
        @edit="edit"
        @delete="deleteData"
      />
    </el-card>

    <Modal v-model:visible="visible" :title="modalTitle" width="500px">
      <ModalForm ref="modalFormRef" :data="modalData" @success="handleSuccess" />
      <template #footer>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </Modal>
    <Modal v-model:visible="visibleTongue" :title="modalTitleTongue" width="500px">
      <ModalTongue
        ref="modalFormRefTongue"
        :data="modalDataTongue"
        @success="handleSuccessTongue"
      />
      <template #footer>
        <el-button type="primary" @click="submitFormTongue">保存</el-button>
      </template>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { BasicTable, TableAction } from '@/components/BasicTable'
import { discountColumns, pointColumns, tongueColumns, actionColumn } from './index.data'
import {
  getBenefitsList,
  createBenefits,
  getBenefitsListTongue,
  updateBenefits,
  deleteBenefits,
  deleteTongueCount,
  saveTongueCount
} from '@/api/member/benefits'
import Modal from '@/components/Modal/index.vue'
import ModalTongue from './ModalTongue.vue'
import ModalForm from './ModalForm.vue'
import TableList from './TableList.vue'
import { ref, onMounted, reactive, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElCard, ElDivider, ElButton } from 'element-plus'
import type { ActionItem } from '@/components/BasicForm/src/types'

const visible = ref<boolean>(false)
const modalTitle = ref<string>('新增')
const modalFormRef = ref<InstanceType<typeof ModalForm>>()
const modalData = ref<any>({})
const discountTableRef = ref<InstanceType<typeof BasicTable>>()
const pointTableRef = ref<InstanceType<typeof BasicTable>>()
const modalType = ref<number>(1)

// 舌诊权益相关变量
const visibleTongue = ref<boolean>(false)
const modalTitleTongue = ref<string>('新增舌诊权益')
const modalFormRefTongue = ref<any>()
const modalDataTongue = ref<any>({})

// 表格数据
const benefitsData = ref<any[]>([])
const pointTableData = ref<any[]>([])
const tongueTableData = ref<any[]>([])
const state = reactive({
  benefitsInfo: {} as any,
  pointTableInfo: {} as any
})

// 加载数据
const loadBenefitsData = async () => {
  try {
    const data = await getBenefitsList()
    state.benefitsInfo = data.find((item: any) => item.benefitsType === 1)
    state.pointTableInfo = data.find((item: any) => item.benefitsType === 2)
    benefitsData.value = state.benefitsInfo?.levelList
    pointTableData.value = state.pointTableInfo?.levelList
  } catch (error) {
    console.error('加载权益数据失败', error)
  }
}
const addTongue = () => {
  modalDataTongue.value = {}
  visibleTongue.value = true
}
const loadTongueData = async () => {
  try {
    const response = await getBenefitsListTongue()
    console.log('舌诊API返回数据:', response)
    // 根据API返回结构调整
    tongueTableData.value = Array.isArray(response) ? response : response.data || []
  } catch (error) {
    console.error('加载舌诊数据失败', error)
    tongueTableData.value = []
  }
}

// 监听舌诊权益弹窗关闭，重置数据
watch(
  () => visibleTongue.value,
  (newVal) => {
    if (!newVal) {
      // 弹窗关闭时重置数据
      setTimeout(() => {
        modalDataTongue.value = {}
      }, 200)
    }
  }
)

// 初始化加载数据
onMounted(() => {
  loadBenefitsData()
  loadTongueData()
})

// 舌诊权益表单提交
const submitFormTongue = () => {
  modalFormRefTongue.value?.submitForm()
}

// 原有API函数保留，用于BasicTable组件，但已不再使用
// 这些函数可以在需要时恢复使用
/*
const getBenefitsListDiscount = (params: any) => {
  return getBenefitsList({
    ...params,
    benefitsType: 1
  })
}

const getBenefitsListPoint = (params: any) => {
  return getBenefitsList({
    ...params,
    benefitsType: 2
  })
}
*/

// 仍在使用的API函数
const getBenefitsTongueList = () => {
  return getBenefitsListTongue()
}

const getActions = (row: Record<string, any>, benefitsType: number, showStatusToggle = true) => {
  // 基本操作：编辑和删除（所有类型都有）
  const actions: ActionItem[] = [
    {
      label: '编辑',
      type: 'text',
      onClick: () => edit(row, benefitsType)
    },
    {
      label: '删除',
      type: 'text',
      onClick: () => deleteData(row, benefitsType)
    }
  ]

  // 仅在需要时添加状态切换操作
  if (showStatusToggle && benefitsType !== 3) {
    actions.splice(1, 0, {
      label: row.status === 0 ? '禁用' : '启用',
      type: 'text',
      style: row.status === 0 ? 'color: #f00' : '',
      onClick: () => changeStatus(row, benefitsType)
    })
  }

  return actions
}

// 替换原有函数
const tableActions = (row: Record<string, any>, benefitsType: number) => {
  console.log('row', row)
  return getActions(row, benefitsType, true)
}

const tongueActions = (row: Record<string, any>, benefitsType: number) =>
  getActions(row, benefitsType, false)

const searchFormActions = (benefitsType: number) => {
  return [{ label: '新增', type: 'primary', onClick: () => add(benefitsType) }]
}

const add = (benefitsType: number) => {
  // 舌诊权益单独处理
  if (benefitsType === 3) {
    // 重置数据
    modalDataTongue.value = {}
    modalTitleTongue.value = '新增舌诊权益'

    // 先显示弹窗
    visibleTongue.value = true

    // 确保在弹窗打开后立即刷新舌诊权益列表数据
    nextTick(() => {
      if (modalFormRefTongue.value && modalFormRefTongue.value.getTongueRightsList) {
        modalFormRefTongue.value.getTongueRightsList()
      }
    })
  } else {
    modalType.value = benefitsType
    modalTitle.value = '新增'
    modalData.value = {
      benefitsType: benefitsType
    }
    visible.value = true
  }
}

const edit = (row: any, benefitsType: number) => {
  // modalType.value = benefitsType
  // 舌诊权益单独处理
  if (benefitsType === 3) {
    // 每次编辑前先清空之前的数据
    modalDataTongue.value = {}
    // 设置延时确保清空操作完成后再赋新值
    setTimeout(() => {
      modalDataTongue.value = {
        count: row.count,
        level: row.level
      }
      modalTitleTongue.value = '编辑舌诊权益'
      visibleTongue.value = true
    }, 0)
  } else {
    visible.value = true
    modalType.value = benefitsType
    modalTitle.value = '编辑'
    modalData.value = {
      ...row,
      benefitsType: benefitsType,
      interestsId: benefitsType === 1 ? state.benefitsInfo.id : state.pointTableInfo.id
    }
  }
}
const changeStatus = (row: any, benefitsType: number) => {
  const sendData = getSendData({ ...row, status: row.status === 0 ? 1 : 0, benefitsType })
  ElMessageBox.confirm('确定要修改状态吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateBenefits(sendData).then(() => {
      ElMessage({
        message: '更新成功',
        type: 'success'
      })
      // 重新加载数据
      loadBenefitsData()
    })
  })
}

const deleteData = (row: any, benefitsType: number) => {
  ElMessageBox.confirm('确定删除该配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (benefitsType === 3) {
        deleteTongueCount(row.level).then(() => {
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
          // 重新加载数据
          loadTongueData()

          // 同时更新ModalTongue组件中的数据
          if (modalFormRefTongue.value && modalFormRefTongue.value.getTongueRightsList) {
            modalFormRefTongue.value.getTongueRightsList()
          }
        })
      } else {
        deleteBenefits(row.id).then(() => {
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
          loadBenefitsData()
        })
      }
    })
    .catch(() => {
      ElMessage({
        message: '取消删除',
        type: 'info'
      })
    })
}

const submitForm = () => {
  modalFormRef.value?.submitForm()
}
const getSendData = (data: any) => {
  if (data.benefitsType === 1) {
    let list = state.benefitsInfo.levelList.map((item) => {
      return { ...item }
    })
    list.forEach((item: any) => {
      if (item.id === data.id) {
        item.benefitValue = data.benefitValue
        item.level = data.level
        item.status = data.status
        item.levelId = data.levelId
      }
    })
    return {
      id: state.benefitsInfo.id,
      benefitsType: 1,
      leveBenefitsListVo: list
    }
  } else if (data.benefitsType === 2) {
    let list = state.pointTableInfo.levelList.map((item) => {
      return { ...item }
    })
    list.forEach((item: any) => {
      if (item.id === data.id) {
        item.benefitValue = data.benefitValue
        item.level = data.level
        item.status = data.status
        item.levelId = data.levelId
      }
    })
    return {
      id: state.pointTableInfo.id,
      benefitsType: 2,
      leveBenefitsListVo: list
    }
  }
}

const handleSuccess = (data: any) => {
  console.log('handleSuccess', data)
  // return
  if (data.id) {
    const sendData = getSendData(data)
    console.log('sendData++++', sendData)
    updateBenefits(sendData).then(() => {
      ElMessage({
        message: '更新成功',
        type: 'success'
      })
      // 重新加载数据
      loadBenefitsData()
    })
  } else {
    const sData = {
      benefitsType: modalType.value,
      leveBenefitsListVo: [
        {
          benefitValue: data.benefitValue,
          levelId: data.levelId,
          level: data.level,
          status: data.status
        }
      ]
    }
    createBenefits(sData).then(() => {
      ElMessage({
        message: '新增成功',
        type: 'success'
      })
      // 重新加载数据
      loadBenefitsData()
    })
  }
  visible.value = false
}

// 舌诊权益处理成功
const handleSuccessTongue = (data: any) => {
  saveTongueCount({
    count: data.count,
    level: data.level
  }).then(() => {
    ElMessage({
      message: '保存成功',
      type: 'success'
    })
    loadTongueData()
    // 关闭弹窗
    visibleTongue.value = false
    // 刷新组件以重新获取舌诊权益列表
    if (modalFormRefTongue.value && modalFormRefTongue.value.getTongueRightsList) {
      modalFormRefTongue.value.getTongueRightsList()
    }
  })
}
</script>

<style scoped lang="scss">
.container-wrapper {
  width: 100%;
  height: 100%;
}

.card-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
